#include "precomp.h"
#include "Bullet.h"
#include "Character.h"

Bullet::Bullet(CL_GraphicContext *gc, CL_Angle angle, CL_Pointf origi, int damage, float range, Map* map, list<Character*> *collide_characters, float speed, float collide_radius, const char* image_path) 
		: GameObject(image_path, gc, map, collide_radius), _angle(angle), _damage(damage), _origi(origi), _speed(speed), _range(range), _collide_characters(collide_characters)
{
	GameObject::set_position(origi.x, origi.y);
	_die = false;
}

void Bullet::tick(float delta_time){
	if(!_die){
		float _sin = sin(_angle.to_radians()), 
			  _cos = cos(_angle.to_radians());

		float x_speed = _speed * _cos,
			  y_speed = _speed * _sin;

		set_position(_x + x_speed * delta_time, _y + y_speed * delta_time);

		if(collide_map() || range_count() >= _range){
			_die = true;
		}else{
			for(list<Character*>::iterator it = _collide_characters->begin(); it != _collide_characters->end(); it++){
				if(collide_character(*it)){
					(*it)->damage(_damage);
					_die = true;

					break;
				}
			}
		}
	}
}

bool Bullet::collide_character(Character *object){
	CL_Pointf object_position(object->get_x(), object->get_y()),
			  self_position(_x, _y);

	float distance = object_position.distance(self_position);

	if(distance <= object->get_collision_radius() +  _collision_radius){
		return true;
	}

	return false;
}

bool Bullet::is_dead(){
	return _die;
}

void Bullet::draw(float ch_x, float ch_y){
	GameObject::draw(_x - ch_x + GameObject::center_x, _y - ch_y + GameObject::center_y);

	//CL_Console::write_line("%1 %2", _x, _y);
}

float Bullet::range_count(){
	return _origi.distance(CL_Pointf(_x, _y));
}

int Bullet::get_damage(){
	return _damage;
}